/**
 *  (c)
 * <p>
 *
 * <p>
 *
 */

package com.nn.smart.bus.cloud;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.nn.smart.bus.commons.tools.exception.NNException;
import com.nn.smart.bus.exception.ModuleErrorCode;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 阿里云存储
 *
 * @author nanning
 */
public class AliyunCloudStorageService extends AbstractCloudStorageService {

    public AliyunCloudStorageService(CloudStorageConfig config) {
        this.config = config;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        OSSClient client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
                config.getAliyunAccessKeySecret());
        try {
            client.putObject(config.getAliyunBucketName(), path, inputStream);
            client.shutdown();
        } catch (Exception e) {
            throw new NNException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }

        return config.getAliyunDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getAliyunPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getAliyunPrefix(), suffix));
    }

    /**
     * 下载阿里云oss服务器上的文件
     *
     * @param url      完整的访问连击
     * @param response
     * @return void
     * @author nanning
     * @date 2019/10/24 14:43
     */
    public void download(String url, HttpServletResponse response) throws IOException {

        OSS ossClient = new OSSClientBuilder().build(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(), config.getAliyunAccessKeySecret());

        String objectName = url.replace(config.getAliyunDomain().concat("/"), "");
        String filename = objectName.substring(objectName.lastIndexOf("/") + 1);
        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = ossClient.getObject(config.getAliyunBucketName(), objectName);
        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        InputStream content = ossObject.getObjectContent();
        if (null != content) {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Pragma", "No-Cache");
            response.setHeader("Cache-Control", "No-Cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("application/msexcel; charset=UTF-8");
            // 设定输出文件头
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            byte[] buf = new byte[1024];

            int L;
            while ((L = content.read(buf)) != -1) {
                toClient.write(buf, 0, L);
            }
            content.close();
            toClient.flush();
            toClient.close();
            ossClient.shutdown();
        }
    }
}
